/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import data_preferences from '@ohos.data.preferences';

type ValueType = number | string | boolean;

export enum Code {
    SUCCESS, FAIL
}

export class PreferencesUtils {
    static CURRENT_TIME: string = 'currentTime'

    static putData(preferencesName: string, key: string, data: ValueType, callback?: any) {
        let promise = data_preferences.getPreferences(globalThis.context, preferencesName)
        promise.then((preferences) => {
            let getPromise = preferences.put(key, data)
            getPromise.then(() => {
                callback(Code.SUCCESS)
            }).catch(() => {
                callback(Code.FAIL)
            })
        }).catch(() => {
            callback(Code.FAIL)
        })
    }

    static getData(preferencesName: string, key: string, defaultData: ValueType, callback: any) {
        let promise = data_preferences.getPreferences(globalThis.context, preferencesName)
        promise.then((preferences) => {
            let getPromise = preferences.get(key, defaultData)
            getPromise.then((value) => {
                callback(value)
            }).catch(() => {
                callback(Code.FAIL)
            })
        }).catch(() => {
            callback(Code.FAIL)
        })
    }
}
